﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using PPI.Client.Logic.Distribution;
using PPI.Client.Logic.XML;
using PPI.Client.Utils;
using PPI.Entities.Distribution;
using PPI.Entities.Enumerator;
using PPI.Entities.XML;
using PPI.General;

namespace PPI.Client.Logic.Upload
{
    public class LUploadStrategyDistributionImages : LUploadStrategyBase
    {
        public LUploadStrategyDistributionImages(EXmlOutboxBase database) : base(database)
        {
        }

        public override void StartWork(BackgroundWorker worker, DoWorkEventArgs workerEvents)
        {
            List<EDistributionPole> lstPoles = LPole.GetDistributionImages(m_OutboxDatabase.ConnectionString);
            WebUploaderHelper _UploaderHelper = new WebUploaderHelper(Constants.K_WEBSITEUPLOADER);

            Int32 _TotalToUpload = 0;

            foreach (EDistributionPole pole in lstPoles)
            {
                foreach (EDistributionPoleImage poleImage in pole.Images)
                    _TotalToUpload += (poleImage.ServerID == Int32.MinValue ? 1 : 0);

                foreach (EMeter meter in pole.Meters)
                    _TotalToUpload += (meter.UploadedImage ? 0 : 1);

                foreach (ETransformer transformer in pole.Transformers)
                    _TotalToUpload += (transformer.UploadedImage ? 0 : 1);
            }

            Int32 _CountUploaded = _TotalToUpload;

            foreach (EDistributionPole pole in lstPoles)
            {
                if (worker.CancellationPending)
                {
                    workerEvents.Cancel = true;
                    return;
                }

                foreach (EDistributionPoleImage image in pole.Images)
                {
                    if (image.ServerID == Int32.MinValue)
                    {
                        try
                        {
                            //Upload pole Images
                            image.ServerID = LPole.SavePoleImage(image, pole.ServerID);

                            string _imageDirectory = DirHelper.GetImagesDirectory(m_OutboxDatabase.ConnectionString);
                            FileInfo file = new FileInfo(_imageDirectory + Path.DirectorySeparatorChar + image.FileName);
                            string _FileName = pole.ServerID + "_" + image.ServerID + ".jpg";
                            string _FolderName = DirHelper.GetImageDirectory(pole.ServerID, image.ServerID);

                            if (file.Exists)
                                _UploaderHelper.Upload(_FolderName, _FileName, file,
                                                       Enum.GetName(typeof (DatabaseTypes),
                                                                    m_OutboxDatabase.DatabaseType));
                        }
                        catch (Exception ex)
                        {
                            RegisterError.SaveError(ex);
                            m_HasErrors = true;
                        }
                        finally
                        {
                            LImage.UpdatePoleImageUploadedData(image, pole.ServerID, m_OutboxDatabase.ConnectionString);
                            _CountUploaded--;
                            worker.ReportProgress(ReportProgress(_CountUploaded, _TotalToUpload));
                        }
                    }
                }


                //Upload meter Image
                foreach (EMeter meter in pole.Meters)
                {
                    if (!meter.UploadedImage)
                    {
                        bool imageUploaded = false;

                        try
                        {
                            string _imageDirectory = DirHelper.GetImagesDirectory(m_OutboxDatabase.ConnectionString);
                            FileInfo file =
                                new FileInfo(_imageDirectory + Path.DirectorySeparatorChar + meter.Image.FileName);
                            string _FileName = pole.ServerID + "_" + meter.ServerId + ".jpg";
                            string _FolderName = DirHelper.GetImageDirectory(pole.ServerID, meter.ServerId);
                            imageUploaded = false;

                            if (file.Exists)
                            {
                                _UploaderHelper.Upload(_FolderName, _FileName, file,
                                                       Enum.GetName(typeof (DatabaseTypes),
                                                                    m_OutboxDatabase.DatabaseType) + "MeterImages");

                                imageUploaded = true;

                                string originalFileName = meter.Image.FileName;
                                meter.Image.FileName = _FileName;
                                LPole.SaveMeterImage(meter.Image, meter.ServerId);
                                meter.Image.FileName = originalFileName;
                            }
                        }
                        catch (Exception ex)
                        {
                            RegisterError.SaveError(ex);
                            m_HasErrors = true;
                        }
                        finally
                        {
                            LImage.UpdateMeterImageUploadedData(meter.Id, imageUploaded,
                                                                m_OutboxDatabase.ConnectionString);
                            _CountUploaded--;
                            worker.ReportProgress(ReportProgress(_CountUploaded, _TotalToUpload));
                        }
                    }
                }

                //Upload transformer Image
                foreach (ETransformer transformer in pole.Transformers)
                {
                    foreach (EDistributionPoleImage image in transformer.Images)
                    {
                        bool imageUploaded = false;

                        try
                        {
                            Int32 idImage = LPole.SaveTransformerImage(image, transformer.ServerId);
                            
                            string _imageDirectory = DirHelper.GetImagesDirectory(m_OutboxDatabase.ConnectionString);
                            FileInfo file = new FileInfo(_imageDirectory + Path.DirectorySeparatorChar + image.FileName);
                            string _FileName = transformer.ServerId + "_" + idImage + ".jpg";
                            string _FolderName = DirHelper.GetImageDirectory(transformer.ServerId, idImage);

                            if (file.Exists)
                                _UploaderHelper.Upload(_FolderName, _FileName, file, Enum.GetName(typeof (DatabaseTypes), m_OutboxDatabase.DatabaseType) + "TransformerImages");
                        }
                        catch (Exception ex)
                        {
                            RegisterError.SaveError(ex);
                            m_HasErrors = true;
                        }
                        finally
                        {
                            _CountUploaded--;
                            worker.ReportProgress(ReportProgress(_CountUploaded, _TotalToUpload));
                        }
                    }
                }

                //Upload sectionalizer Image
                foreach (ESectionalizer sectionalizer in pole.Sectionalizers)
                {
                    foreach (EDistributionPoleImage image in sectionalizer.Images)
                    {
                        bool imageUploaded = false;

                        try
                        {
                            Int32 idImage = LPole.SaveSectionalizerImage(image, sectionalizer.ServerId);

                            string _imageDirectory = DirHelper.GetImagesDirectory(m_OutboxDatabase.ConnectionString);
                            FileInfo file = new FileInfo(_imageDirectory + Path.DirectorySeparatorChar + image.FileName);
                            string _FileName = sectionalizer.ServerId + "_" + idImage + ".jpg";
                            string _FolderName = DirHelper.GetImageDirectory(sectionalizer.ServerId, idImage);

                            if (file.Exists)
                                _UploaderHelper.Upload(_FolderName, _FileName, file, Enum.GetName(typeof(DatabaseTypes), m_OutboxDatabase.DatabaseType) + "SectionalizerImages");
                        }
                        catch (Exception ex)
                        {
                            RegisterError.SaveError(ex);
                            m_HasErrors = true;
                        }
                        finally
                        {
                            _CountUploaded--;
                            worker.ReportProgress(ReportProgress(_CountUploaded, _TotalToUpload));
                        }
                    }
                }

                //Upload recloser Image
                foreach (ERecloser recloser in pole.Reclosers)
                {
                    foreach (EDistributionPoleImage image in recloser.Images)
                    {
                        bool imageUploaded = false;

                        try
                        {
                            Int32 idImage = LPole.SaveRecloserImage(image, recloser.ServerId);

                            string _imageDirectory = DirHelper.GetImagesDirectory(m_OutboxDatabase.ConnectionString);
                            FileInfo file = new FileInfo(_imageDirectory + Path.DirectorySeparatorChar + image.FileName);
                            string _FileName = recloser.ServerId + "_" + idImage + ".jpg";
                            string _FolderName = DirHelper.GetImageDirectory(recloser.ServerId, idImage);

                            if (file.Exists)
                                _UploaderHelper.Upload(_FolderName, _FileName, file, Enum.GetName(typeof(DatabaseTypes), m_OutboxDatabase.DatabaseType) + "RecloserImages");
                        }
                        catch (Exception ex)
                        {
                            RegisterError.SaveError(ex);
                            m_HasErrors = true;
                        }
                        finally
                        {
                            _CountUploaded--;
                            worker.ReportProgress(ReportProgress(_CountUploaded, _TotalToUpload));
                        }
                    }
                }

            //worker.ReportProgress(ReportProgress(0, _TotalToUpload));

                if (worker.CancellationPending)
                {
                    workerEvents.Cancel = true;
                    return;
                }

            }
            
            System.Threading.Thread.Sleep(100);
        }

        public override void FinishWork()
        {
            LXmlOutbox _serviceLogic = new LXmlOutbox(m_OutboxDatabase);
            _serviceLogic.CopyToSentFolder();
        }

    }
}
